package com.mrdeer.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author ：xie jianchu
 * @date ：Created in 2020/9/25 0025 10:53
 */
public class Server {
    public static void main(String[] args) throws InterruptedException {
        //Configure the server
        //创建两个EventLoopGroup对象
        //创建boss线程组 用于服务端接受客户端的链接
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //创建worker线程组，用于进行SocketChannel的数据读写
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建ServerBootstrap对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //设置使用的 EventLoopGroup
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)                  //设置要实例化的为NioServerSocketChannel类
                    .handler(new LoggingHandler(LogLevel.INFO))             //设置NioServerSocketChannel的处理类
                    .childHandler(new ServerInitializer());                 //设置连入服务端的Client的SocketChannel的处理器
            //绑定端口，并同步等待成功，即启动服务端
            ChannelFuture future = bootstrap.bind(8888);
            //监听服务端关闭，并阻塞等待
            future.channel().closeFuture().sync();
        } finally {
            //优雅的关闭两个EventLoopGroup对象
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
